package com.workcell.workdata.im.component.redis;

import com.workcell.workdata.im.entity.Group;
import com.workcell.workdata.im.entity.proto.GroupProto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class GroupRedisTemplate extends RedisTemplate<String, Group> implements RedisSerializer<Group> {

	private static final String CACHE_PREFIX = "GROUP_";

	@Autowired
	public GroupRedisTemplate(RedisConnectionFactory connectionFactory) {

		StringRedisSerializer stringSerializer = new StringRedisSerializer();

		setKeySerializer(stringSerializer);
		setHashKeySerializer(stringSerializer);

		setValueSerializer(this);
		setHashValueSerializer(this);

		setConnectionFactory(connectionFactory);
		afterPropertiesSet();
	}

	public void save(Group group) {
		String key = CACHE_PREFIX + group.getId();
		super.boundValueOps(key).set(group);
	}

	public Group get(long id) {
		String key = CACHE_PREFIX + id;
		return super.boundValueOps(key).get();
	}

	public void remove(long id) {
		String key = CACHE_PREFIX + id;
		super.delete(key);
	}


	@Override
	public byte[] serialize(Group group) throws SerializationException {
		GroupProto.Model.Builder builder = GroupProto.Model.newBuilder();

		builder.setId(group.getId());
		builder.setName(group.getName());
		builder.setUid(group.getUid());
		builder.setState(group.getState());
		builder.setTimestamp(group.getCreateTime().getTime());
		if(group.getNotice() != null){
			builder.setNotice(group.getNotice());
		}
		return builder.build().toByteArray();
	}

	@Override
	public Group deserialize(byte[] bytes) throws SerializationException {

		try {

			GroupProto.Model proto = GroupProto.Model.parseFrom(bytes);
			Group group = new Group();
			group.setId(proto.getId());
			group.setName(StringUtils.trimToNull(proto.getName()));
			group.setState((byte)proto.getState());
			group.setNotice(StringUtils.trimToNull(proto.getNotice()));
			group.setUid(proto.getUid());
			group.setCreateTime(new Date(proto.getTimestamp()));

			return group;

		} catch (Exception error) {
			return  null;
		}
	}
}
